﻿using CommunityToolkit.Mvvm.Input;
using Koala.Pro.Common;
using Koala.Pro.Helpers;
using Koala.Pro.Models;
using Koala.Pro.ViewModels;
using System.Data;
using System.Windows;
using System.Windows.Input;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages
{
    public partial class ImportExcelPage : Window, INavigableView<ImportExcelViewModel>
    {
        public delegate Task<bool> SaveDataHandler(DataRow dr);

        public event SaveDataHandler OnDataSave;

        public ImportExcelViewModel ViewModel { get; }

        public ImportExcelPage(ImportExcelViewModel viewModel)
        {
            ViewModel = viewModel;
            base.DataContext = this;
            InitializeComponent();
        }

        private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                DragMove();
            }
        }

        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                base.WindowState = WindowState.Normal;
            }
        }

        [RelayCommand]
        private void BrowseExcel()
        {
            string text = FileDialogHelper.OpenExcel();
            if (!string.IsNullOrEmpty(text))
            {
                ViewModel.ImportFilePath = text;
                ViewData();
            }
        }

        [RelayCommand]
        private async Task<CommonResult> SaveData()
        {
            if (ViewModel.Items != null)
            {
                DataTable items = ViewModel.Items;
                if (items == null || items.Rows?.Count != 0)
                {
                    if (MessageDxUtil.ShowYesNoAndWarning("该操作将把数据导入到系统数据库中，您确定是否继续？") == System.Windows.MessageBoxResult.Yes)
                    {
                        DataTable dt = ViewModel.Items;
                        int itemCount = 0;
                        int errorCount = 0;
                        foreach (DataRow row in dt.Rows)
                        {
                            try
                            {
                                if (await this.OnDataSave(row))
                                {
                                    itemCount++;
                                }
                            }
                            catch (Exception ex)
                            {
                                errorCount++;
                                LogTextHelper.Error(ex);
                                MessageDxUtil.ShowError(ex.Message);
                            }
                            if (errorCount >= 3)
                            {
                                string key = "记录导入已经连续出错超过[{0}]条，您是否确定退出导入操作？\r\n单击【是】退出导入，单击【否】忽略错误，继续导入下一记录。";
                                key = JsonLanguage.Default.GetString(key);
                                if (MessageDxUtil.ShowYesNoAndWarning(string.Format(key, errorCount)) == System.Windows.MessageBoxResult.Yes)
                                {
                                    break;
                                }
                                errorCount = 0;
                            }
                        }
                        new CommonResult();
                        return (itemCount != dt.Rows.Count) ? new CommonResult(success: true, "操作完成，有错误可能未导入全部") : new CommonResult(success: true, "操作成功");
                    }
                    return new CommonResult(success: false);
                }
            }
            return new CommonResult(success: false);
        }

        private void ViewData()
        {
            if (txtFilePath.Text == "")
            {
                MessageDxUtil.ShowTips("请选择指定的Excel文件");
                return;
            }
            try
            {
                DataSet dataset = new DataSet();
                string error = "";
                AsposeExcelTools.ExcelFileToDataSet(txtFilePath.Text, out dataset, out error);
                ViewModel.Items = dataset.Tables[0];
            }
            catch (Exception ex)
            {
                LogTextHelper.Error(ex);
                MessageDxUtil.ShowError(ex.Message);
            }
        }

        private void btnWindowClose_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        [RelayCommand]
        private void Back()
        {
            Close();
        }
    }
}
